/// ****************************************************************************
/// Author:	        Robin Zhu
/// Create Date:	2012-2-14
/// Purpose: 		带Key记录的集合类定义文件
/// ****************************************************************************
/// Modify By		Date			Remark
/// Robin           2012-11-10      增加更新某个对象的方法
/// Robin           2013-1-23       重新实现KeyedRecordSet的Remove虚方法
/// ****************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RB.Domain.Models;
using RB.DataAccess;

namespace RB.Domain.RelationalMapping
{
    /// <summary>
    /// 带Key记录的集合类
    /// </summary>
    /// <typeparam name="T">领域模型实体对象类型</typeparam>
    /// <typeparam name="TKey">主键数据类型</typeparam>
    public class IdKeyedRecordSet<TItem, TKey> : KeyedRecordSet<TItem, TKey>
        where TItem : class, IIdKeyed<TKey>
    {
        /// ****************************************************************************
        #region 自定义方法

        public bool Update(TItem item)
        {
            return Update(item, DataContext.CreateExecutor());
        }

        public virtual bool Update(TItem item, Executor executor)
        {
            int count = base.Update(p => item, p => p.Id.Equals(item.Id), executor);
            return count > 0;
        }

        #endregion 自定义方法

        /// ****************************************************************************
        #region 重写KeyedRecordSet方法

        public override TItem this[TKey key]
        {
            get
            {
                using (Executor exec = DataContext.CreateExecutor())
                {
                    var q = from p in exec.Query<TItem>()
                            where p.Id.Equals(key)
                            select p;
                    return q.SingleOrDefault();
                }
            }
            set
            {
                using (Executor exec = DataContext.CreateExecutor())
                {
                    exec.Update(value, p => p.Id.Equals(key));
                }
            }
        }

        public override bool Contains(TItem item)
        {
            return this.Any(p => p.Id.Equals(item.Id));
        }

        public override bool Remove(TItem item, Executor exec)
        {
            int n = this.RemoveAll(p => p.Id.Equals(item.Id), exec);
            return n > 0;
        }

        #endregion 重写KeyedRecordSet方法
    }
}
